<template>
  <div class="l-rblock">
    <div v-show="steps(0)" class="l-rblock" style="padding:24px;">
      <div class="l-page-panel">
        <el-form :model="formData" :rules="rules" size="mini" ref="baseInfo" label-width="80px">
          <el-col :span="24">
            <el-form-item :label="$t('编号')" prop="f_Code">
              <el-input v-model="formData.f_Code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('名称')" prop="f_Name">
              <el-input v-model="formData.f_Name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('图标')" prop="f_Icon">
              <l-input-icon :iconList="lr_icons" v-model="formData.f_Icon">
              </l-input-icon>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('表单选择')" prop="f_FormCode">
              <l-custmerform-select
                  v-model="formData.f_FormCode"
                  @change="custmerformChange"
                  :placeholder="$t('请选择')"
              >
              </l-custmerform-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('表单版本')" prop="f_FormVerison">
              <l-select
                  v-model="formData.f_FormVerison"
                  :options="formVerisons"
                  :placeholder="$t('请选择')"
              >
              </l-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('上级')" prop="f_PModuleId">
              <l-tree-select
                  v-model="formData.f_PModuleId"
                  :options="modulesExpandTree">
              </l-tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('排序')" prop="f_SortCode">
              <el-input-number v-model="formData.f_SortCode" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('状态')">
              <el-switch
                  :active-value="1"
                  :inactive-value="0"
                  v-model="formData.f_EnabledMark"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('描述')" prop="f_Description">
              <el-input type="textarea" v-model="formData.f_Description"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
    </div>
    <div v-show="steps(1)" class="l-rblock">
      <l-layout class="l-tab-page">
        <l-panel>
          <div class="l-auto-window">
            <el-tabs v-model="pageActiveName" :stretch="true">
              <el-tab-pane :label="$t('布局设置')" name="tab01">
                <webcode-layout></webcode-layout>
              </el-tab-pane>
              <el-tab-pane v-if="config.layoutType == 2" :label="$t('左侧树形设置')" name="tab05">
                <webcode-lefttree :colslist="colslist"></webcode-lefttree>
              </el-tab-pane>
              <el-tab-pane :label="$t('列表设置')" name="tab02">
                <webcode-columns ref="columnsOp" :columnsTree="columnsTree"></webcode-columns>
              </el-tab-pane>
              <el-tab-pane :label="$t('查询设置')" name="tab03">
                <webcode-query ref="queryOp" :queryTree="queryTree"></webcode-query>
              </el-tab-pane>
              <el-tab-pane :label="$t('按钮设置')" name="tab04">
                <webcode-btns :formType="(formScheme && formScheme.formType==1)?1:0" ref="btnOp" :columnsTree="columnsTree"></webcode-btns>
              </el-tab-pane>
            </el-tabs>
          </div>
        </l-panel>
      </l-layout>
    </div>
  </div>
</template>
<script>
import {mapGetters} from "vuex";

const api = window.$api.custmerForm.scheme

import webcodeLayout from './config/layout'
import webcodeLefttree from './config/leftTree'
import webcodeColumns from './config/columns'
import webcodeQuery from './config/query'
import webcodeBtns from './config/btns'

export default {
  provide() {
    return {
      formConfig: this.config
    };
  },
  props: {
    stepActive: {
      type: Number,
      default: 0
    }
  },
  components: {
    webcodeLayout,
    webcodeLefttree,
    webcodeColumns,
    webcodeQuery,
    webcodeBtns
  },
  data() {
    return {
      pageActiveName: 'tab01',
      columnsTree: [
        {
          label: '全选',
          children: []
        }
      ],
      queryTree: [
        {
          label: '全选',
          children: []
        }
      ],
      colslist: [],
      config: {
        layoutType: 1,
        queryType: '1',
        btns: [
          {label: '新增', id: 'Add', prop: 'Add', icon: 'el-icon-plus', isRowBtn: false},
          {label: '导入', id: 'Import', prop: 'Import', icon: 'el-icon-upload2', isRowBtn: false},
          {label: '导出', id: 'Export', prop: 'Export', icon: 'el-icon-download', isRowBtn: false},
          {label: '编辑', id: 'Edit', prop: 'Edit', isRowBtn: true},
          {label: '删除', id: 'Delete', prop: 'Delete', isRowBtn: true},
          {label: '详情', id: 'Details', prop: 'Details', isRowBtn: true},
        ],
        left: {
          title: '左侧树形',
          colField: '',
          dataType: '1',
          dataIdKey: '',
          dataPIdKey: '',
          dataValueKey: '',
          dataLabelKey: '',
          colNames: [], // 数据源字段列表
          options: [],  // 静态数据
          dataCode: ''
        },
        table: {
          isPage: true,
          columns: [],
          querys: [],
          sidx: '',
          isDESC: false,
          isDeleteMore: false,
        }
      },
      formData: {
        f_Type: 1,
        f_Code: '',
        f_Name: '',
        f_Icon: 'learun-icon-star',
        f_FormCode: '',
        f_FormVerison: '',
        f_PModuleId: '',
        f_ModuleId: '',
        f_SortCode: '',
        f_EnabledMark: 1,
        f_Description: ''
      },
      rules: {
        f_Code: [
          {required: true, message: '请输入编号', trigger: 'blur'},
          { pattern: /^[A-Za-z][A-Za-z0-9_]*$/ , message: this.$t('请以字母开头填写字母、数字或下划线'), trigger: ["blur", "change"]},
          {
            validator: this.lr_existDbFiled, keyValue: () => {
              return this.formData.f_ModuleId
            }, tableName: 'lr_base_module', fieldName: 'f_EnCode', keyName: 'f_ModuleId', trigger: 'null'
          }
        ],
        f_Name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        f_Icon: [
          {required: true, message: '请选择图标', trigger: 'blur'}
        ],
        f_FormCode: [
          {required: true, message: '请选择表单', trigger: 'blur'}
        ],
        f_FormVerison: [
          {required: true, message: '请选择表单版本'}
        ],
      },
      moreDeleteType: false,
      formScheme: null,
    };
  },
  asyncComputed: {
    formVerisons: {
      async get() {
        let res = []
        if (!this.$validatenull(this.formData.f_FormCode)) {
          res = await this.$awaitWraper(api.getHistoryList(this.formData.f_FormCode))
        }
        return (res || []).map(t => {
          return {label: this.lr_dateFormat(t.f_CreateDate), value: t.f_Id}
        })
      }
    }
  },
  computed: {
    ...mapGetters(["modulesExpandTree"]),
  },

  methods: {
    steps(num) {
      return this.stepActive == num
    },
    handleChangeLayoutType(type) {
      this.config.layoutType = type;
    },
    custmerformChange(val) {
      if (val == null) {
        this.formData.f_FormVerison = ''
      } else {
        this.formData.f_FormVerison = val.f_SchemeId
      }
    },
    // 表单验证
    validateSteps() {
      return new Promise((resolve) => {
        this.$refs.baseInfo.validate(async (valid) => {
          if (valid) {
            const {f_Scheme} = (await this.$awaitWraper(api.getHistory(this.formData.f_FormVerison))) || {}

            this.formScheme = JSON.parse(f_Scheme)

            if (this.formScheme.formType == 1) {// 如果是视图表单就关闭部分按钮
              this.config.btns = this.config.btns.filter(t => ['Import', 'Export', 'Details'].includes(t.id))
            }

            const columns = []
            this.formScheme.formInfo.tabList.forEach(tab => {
              columns.push(...tab.components.filter(t => !['gridtable', 'divider', 'password', 'viewtable', 'card', 'tab', 'collapse','tableLayout', 'btn', 'qrcode', 'barcode'].includes(t.type)))
            })

            const colunmsMap = {}
            columns.forEach(item => {
              colunmsMap[item.prop] = item
            })


            this.columnsTree[0].children = columns.map(t => {
              return {id: t.prop, prop: t.prop, label: t.label, width: 120, align: 'left', isMinWidth: false}
            })

            // 1.获取表格列
            // 2.过滤掉已选列中在表格列中找不到的列
            let columnsChecked = this.config.table.columns.filter(t => this.columnsTree[0].children.findIndex(t2 => t2.prop == t.prop) != -1)
            columnsChecked.forEach(t => {
              t.label = colunmsMap[t.prop].label
            })

            this.config.table.columns = columnsChecked //this.columnsTree[0].children.filter(t=>columnsChecked.findIndex(t2=>t2.prop == t.prop) != -1);


            this.queryTree[0].children = columns.filter(t => !['upload', 'uploadimg', 'password', 'timerange', 'datetimerange', 'count'].includes(t.type)).map(t => {
              return {id: t.prop, prop: t.prop, label: t.label}
            });
            let queryChecked = this.config.table.querys.filter(t => this.queryTree[0].children.findIndex(t2 => t2.prop == t.prop) != -1)
            queryChecked.forEach(t => {
              t.label = colunmsMap[t.prop].label
            })

            this.config.table.querys = queryChecked;


            this.colslist = columns.map(t => {
              return {value: t.prop, label: t.label}
            });
            if (this.colslist.findIndex(t => t.value == this.config.left.colField) == -1) {
              this.config.left.colField = '';
            }


            this.$nextTick(() => {
              this.$refs.columnsOp.setCheckedKeys(columnsChecked.map(t => t.prop));
              this.$refs.queryOp.setCheckedKeys(queryChecked.map(t => t.prop));
              this.$refs.btnOp.setCheckedKeys(this.config.btns.map(t => t.id));


              this.$refs.columnsOp.init()
            })


          }
          resolve(valid)
        })
      })
    },

    // 表单方法
    resetForm() {
      this.formData.f_ModuleId = ''
      this.pageActiveName = 'tab01'
      this.$refs.baseInfo && this.$refs.baseInfo.resetFields()
      this.config.layoutType = 1
      this.config.queryType = '1'
      this.config.btns = [
        {label: '新增', id: 'Add', prop: 'Add', icon: 'el-icon-plus', isRowBtn: false},
        {label: '导入', id: 'Import', prop: 'Import', icon: 'el-icon-upload2', isRowBtn: false},
        {label: '导出', id: 'Export', prop: 'Export', icon: 'el-icon-download', isRowBtn: false},
        {label: '编辑', id: 'Edit', prop: 'Edit', isRowBtn: true},
        {label: '删除', id: 'Delete', prop: 'Delete', isRowBtn: true},
        {label: '详情', id: 'Details', prop: 'Details', isRowBtn: true},
        {label:'发起流程',id:'SelectionProcess',prop:'SelectionProcess',isRowBtn:true},
      ]
      this.config.left = {
        title: '左侧树形',
        colField: '',
        dataType: '1',
        dataIdKey: '',
        dataPIdKey: '',
        dataValueKey: '',
        dataLabelKey: '',
        colNames: [], // 数据源字段列表
        options: [],  // 静态数据
        dataCode: ''
      }
      this.config.table = {
        isPage: true,
        columns: [],
        querys: [],
        sidx: '',
        isDESC: false,
      }
    },
    setForm(data) {
      this.formData = data
      const scheme = JSON.parse(data.f_Scheme)

      this.config.layoutType = scheme.layoutType;
      this.config.queryType = scheme.queryType;
      this.config.btns = scheme.btns
      this.config.left = scheme.left
      this.config.table = scheme.table
    },
    getForm() {
      const postData = {}

      const formData = this.$deepClone(this.formData)
      formData.f_Scheme = JSON.stringify(this.$deepClone(this.config))

      postData.entity = formData
      postData.moduleEntity = {
        f_EnCode: formData.f_Code,
        f_FullName: formData.f_Name,
        f_ParentId: formData.f_PModuleId,
        f_Icon: formData.f_Icon,
        f_Target: 'custmerForm',
        f_IsMenu: 1,
        f_DeleteMark: 0,
        f_UrlAddress: `${formData.f_Code}`,
        f_EnabledMark: formData.f_EnabledMark,
        f_SortCode: formData.f_SortCode
      }

      postData.moduleButtonEntitys = []
      this.config.btns.forEach(btn => {
        postData.moduleButtonEntitys.push({f_EnCode: btn.prop, f_FullName: btn.label})
      })
      if (this.config.layoutType == 2 && this.config.left.dataType == '2') {
        postData.moduleButtonEntitys.push({f_EnCode: 'classifysSetting', f_FullName: '分类管理'})
      }

      const componentMap = {}
      postData.moduleFormEntitys = []
      this.formScheme.formInfo.tabList.forEach(tab => {
        tab.components.forEach(component => {
          componentMap[component.prop] = component
          if (!['gridtable', 'divider', 'card', 'tab', 'collapse','tableLayout'].includes(component.type) && component.display) {
            postData.moduleFormEntitys.push({f_EnCode: component.prop, f_FullName: component.label})
          } else if (['gridtable'].includes(component.type)) {
            postData.moduleFormEntitys.push(...component.children.map(t => {
              return {
                f_EnCode: `${component.prop}|${t.prop}`,
                f_FullName: `${component.label || this.$t('表格')}-${t.label}`
              }
            }))

            postData.moduleFormEntitys.push({
              f_EnCode: `${component.prop}_add`,
              f_FullName: `${component.label || this.$t('表格')}-${this.$t("添加按钮")}`
            })

            postData.moduleFormEntitys.push({
              f_EnCode: `${component.prop}_remove`,
              f_FullName: `${component.label || this.$t('表格')}-${this.$t("删除按钮")}`
            })
          } else if (['divider'].includes(component.type)) {
            postData.moduleFormEntitys.push({
              f_EnCode: component.prop,
              f_FullName: `${component.label}-${component.html}`
            })
          }
        })
      })

      postData.moduleColumnEntitys = []
      this.config.table.columns.forEach(column => {
        const columnComponent = componentMap[column.prop]
        const enCode = `${columnComponent.field}${this.formScheme.formType == 1 ? '' : this.formScheme.db.findIndex(t => t.name == columnComponent.table)}`
        postData.moduleColumnEntitys.push({f_EnCode: enCode, f_FullName: column.label})
      })

      return postData
    },
  }
}
</script>